package com.sise.cn.dao.init;

import com.sise.cn.dao.base.BaseMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName InitDatabase
 * @Description
 * @Author CCJ
 * @Date 2020/6/15 13:23
 **/
@Slf4j
@Component
public class InitDatabase {

    @Autowired
    private BaseMapper baseMapper;

    @PostConstruct
    public void init() {
        log.info("------------------start init databases-----------------");
        if (StringUtils.isEmpty(baseMapper.getDb())) {
            log.error("请配置数据库参数");
            System.exit(-1);
        }
        boolean exist = baseMapper.existDatabase(baseMapper.getDb());
        if (exist) {
            log.info("数据库已存在不需要初始化");
            return;
        }
        try {
            PathMatchingResourcePatternResolver path = new PathMatchingResourcePatternResolver();
            String sqlPath = "classpath*:" + baseMapper.getDb() + "/init/*.sql";
            Resource[] res = path.getResources(sqlPath);
            if (res.length <= 0) {
                return;
            }
            int len;
            byte[] bytes;
            for (Resource resource : res) {
                InputStream is = resource.getInputStream();
                len = is.available();
                bytes = new byte[len];
                is.read(bytes);
                String sql = new String(bytes, StandardCharsets.UTF_8);
                sql = sql.replace("${db}", baseMapper.getDb());
                log.debug("sql=\n{}", sql);
                baseMapper.executor(sql);
            }
            log.info("init databases success");
        } catch (Exception e) {
            log.error("初始化数据库失败，请确认数据库信息是和初始化脚本是否正确");
            log.error("", e);
            System.exit(-1);
        }
    }

}
